//
//  FriendCircleViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/11/6.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "FriendCircleViewController.h"
#import "SayCommentTableViewCell.h"
#import "SendFriendCircleViewController.h"
#import "XHInputView.h"
#import "PhotoBrowseViewController.h"
#import "TZImagePickerController.h"

@interface FriendCircleViewController ()<XHInputViewDelagete,TZImagePickerControllerDelegate>
@property(nonatomic,strong) UIImageView * headImageView;
@property(nonatomic,strong)UIView * tableHeaderView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray * commentArray;

@property (nonatomic, strong) XHInputView *inputViewStyleDefault;

@end

@implementation FriendCircleViewController
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)commentArray
{
    if (!_commentArray) {
        _commentArray=[NSMutableArray array];
    }
    return _commentArray;
}
-(UIView *)tableHeaderView{
    if (!_tableHeaderView) {
        _tableHeaderView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,kScreenW, kScreenH / 4)];
        _tableHeaderView.userInteractionEnabled=YES;
    }
    return _tableHeaderView;
}

-(UIImageView *)headImageView{
    if (!_headImageView) {
        _headImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH / 4)];
//        _headImageView.autoresizingMask=UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; //自动调整view的高度，以保证上边距和下边距不变,自动调整view的宽度，保证左边距和右边距不变
        _headImageView.clipsToBounds=YES;
        _headImageView.userInteractionEnabled=YES;
        _headImageView.contentMode=UIViewContentModeScaleAspectFill;
        _headImageView.backgroundColor = [UIColor whiteColor];
    }
    return _headImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    self.title = @"校园圈";
    if (![[JHUserInfo getUserInfo].role_type isEqualToString:@"5"] && ![[JHUserInfo getUserInfo].role_type isEqualToString:@"6"] && ![[JHUserInfo getUserInfo].role_type isEqualToString:@"7"]) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithImage:[UIImage imageNamed:@"publish"] highlighted:[UIImage imageNamed:@"publish"] target:self selector:@selector(publish)];
    }
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    CGRect rect = self.view.bounds;
    rect.size.height -= 45 + 69;
    self.tableView.frame = rect;
    
    [self creatHeadView];
    [self setupRefresh];//刷新

    
}
#pragma mark - 上传背景图片
- (void)editBackgroundImage:(UIGestureRecognizer *)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message: [NSString stringWithFormat:@"确定更换封面吗？"] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        // You can get the photos by block, the same as by delegate.
        // 你可以通过block或者代理，来得到用户选择的照片.
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
            [self uploadBackgroundImage:photos[0]];
            self.headImageView.image = photos[0];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
#pragma mark - 上传图片接口
- (void)uploadBackgroundImage:(UIImage *)image{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[JSPathUtil urlAppFriendUploadCover] parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (image) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", str];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        }
    } error:nil];
    
    AFURLSessionManager *manager=[[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          MyLog(@"Error: %@", error);
                      } else {
                          MyLog(@"%@ %@", response, responseObject);
                          [Global showActivityWithView:self.view withText:@"修改校园圈背景成功"];
                      }
                  }];
    
    [uploadTask resume];
}
- (void)creatHeadView{
    [self.tableHeaderView addSubview:self.headImageView];
    self.tableView.tableHeaderView = self.tableHeaderView;
    
    self.headImageView.userInteractionEnabled = YES;
    [self.headImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editBackgroundImage:)]];
    //背景图
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [yjNetWorkManger requestType:GET andURL:[JSPathUtil urlAppFriendGetFriendCover] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [self.headImageView sd_setImageWithURL:[NSURL URLWithString: response[@"img"]] placeholderImage:KDEFAULTHEAD];
        }
    }];
    
//    self.headImageView.image = [UIImage imageNamed:@"MyCenter_Headerbg_login"];
    UIImageView *iconImage = [[UIImageView alloc]init];
    iconImage.frame = CGRectMake( (kScreenW - 80)/2, 35, 80, 80);
    iconImage.clipsToBounds = YES;
    iconImage.layer.cornerRadius = 40;
    iconImage.layer.borderColor = [UIColor whiteColor].CGColor;
    iconImage.layer.borderWidth = 2;
    if (!strIsEmpty([JHUserInfo getUserInfo].icon)) {
        [iconImage sd_setImageWithURL:[NSURL URLWithString: [JHUserInfo getUserInfo].icon] placeholderImage:KDEFAULTHEAD];
       
    }else{
        iconImage.image = KDEFAULTHEAD;
    }
    iconImage.backgroundColor = [UIColor clearColor];
    [self.tableHeaderView addSubview:iconImage];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.frame = CGRectMake(0, CGRectGetMaxY(iconImage.frame) + 5, kScreenW, 25);
    nameLabel.text = [JHUserInfo getUserInfo].nick_name;
//    nameLabel.text = @"机器猫";
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.font = [UIFont systemFontOfSize:18];
    [self.tableHeaderView addSubview:nameLabel];
    
}
- (void)creatDataList{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[NSString stringWithFormat:@"%ld",(long)self.pageNo] forKey:@"page"];   //页数 默认1
    [dic setValue:KREFRESHROWS forKey:@"rows"];   //每页数量
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [yjNetWorkManger requestType:GET andURL:[JSPathUtil urlAppFriendGetFriendTopic] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            if (self.pageNo == 1) {
                [self.dataArray removeAllObjects];
            }
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
            for (int i = 0; i < [dic[@"list"] count]; i++) {
                CommentFrame *commentf=[[CommentFrame alloc]init];
                [CommentInfo mj_setupObjectClassInArray:^NSDictionary *{
                    return @{@"comment_list":@"ReplayInfo"};
                }];
                commentf.commentinfo=[CommentInfo mj_objectWithKeyValues:dic[@"list"][i]];
                [self.dataArray addObject:commentf];
            }
            [self refreshCount:self.dataArray.count noDataText:@"还没有朋友圈" totalRow:response[@"totalRow"]];

            [self.tableView reloadData];
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SayCommentTableViewCell *cell=[SayCommentTableViewCell cellWithTableView:tableView];
    
    cell.commentframe=self.dataArray[indexPath.section];
    __weak typeof(self) weakSelf = self;
    cell.scanBigPictureBlack=^(NSArray *bigsPictureArray,NSInteger selectNum){
        PhotoBrowseViewController *photo = [[PhotoBrowseViewController alloc] initWithimageArray:[[NSMutableArray alloc]initWithArray:bigsPictureArray] withIndex:selectNum withType:0];
        photo.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:photo];
        [self presentViewController:nc animated:YES completion:nil];
    };
    cell.clickTypeBlaock=^(ClickType type, CommentInfo *commentinfo,NSInteger repNum){
        if (type==ClickZan) {
            [weakSelf clickZan:commentinfo andindexPath:indexPath];
        }
        if (type==ClickReplay) {
            [weakSelf clickReplay:commentinfo andindexPath:indexPath replayNum:repNum];
        }
    };
    cell.deleteReplayBlack=^(ReplayInfo *replayInfo,NSInteger repNum){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            return;
        }];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf deleteReplay:replayInfo andindexPath:indexPath replayNum:repNum];   //删除回复
        }];
        [alert addAction:cancel];
        [alert addAction:sure];
        [weakSelf presentViewController:alert animated:YES completion:nil];
        
    };
    cell.deleteCommentBlack=^(CommentInfo *commentInfo){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            return;
        }];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf deleteComment:commentInfo andindexPath:indexPath];   //删除回复
        }];
        [alert addAction:cancel];
        [alert addAction:sure];
        [weakSelf presentViewController:alert animated:YES completion:nil];
    };
    cell.scanMoreBlack = ^(CommentInfo *commentInfo) {
        WebViewController *webView = [[WebViewController alloc]initWithTitle:commentInfo.name withRequest:commentInfo.url];
        [weakSelf.navigationController pushViewController:webView animated:YES];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentFrame *commentf=self.dataArray[indexPath.section];
    return commentf.cellheight ;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenW, 10);
//    view.backgroundColor = KBACKGROUNDCOLOR;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.01f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    CGPoint offset = scrollView.contentOffset;
//    if (offset.y < 0) {
//        CGRect rect =self.tableHeaderView.frame;
//        rect.origin.y = offset.y;
//        rect.size.height =CGRectGetHeight(rect)-offset.y;
//        self.headImageView.frame = rect;
//        self.tableHeaderView.clipsToBounds=NO;
//    }
//}

#pragma mark -------------- 校园圈评论点赞/取消赞
- (void)clickZan:(CommentInfo *)commentinfo andindexPath:(NSIndexPath *)indexPath{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSString *url ;
    if ([commentinfo.praise_history isEqualToString:@"0"]) {
        url = [JSPathUtil urlAppFriendAddPraise];
    }else{
        url = [JSPathUtil urlAppFriendDeletePraise];
    }
    [dic setValue:commentinfo.topic_id forKey:@"otherId"];   //动态的topicId 赞目标id
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    
    [yjNetWorkManger requestType:POST andURL:url andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            if ([commentinfo.praise_history isEqualToString:@"0"]) {
                [Global showActivityWithView:self.view withText:@"点赞成功"];
                commentinfo.parise_count = [NSString stringWithFormat:@"%d",[commentinfo.parise_count intValue] + 1];
                NSMutableDictionary *userDic = [[NSMutableDictionary alloc]init];
                userDic[@"user_id"]=[JHUserInfo getUserInfo].userId;
                userDic[@"nick_name"]=[JHUserInfo getUserInfo].nick_name;
                userDic[@"icon"]=[JHUserInfo getUserInfo].icon;
                userDic[@"name"]=[JHUserInfo getUserInfo].name;
                [commentinfo.pariseList addObject:userDic];
                commentinfo.praise_history = @"1";
            }else{
                [Global showActivityWithView:self.view withText:@"取消赞成功"];
                commentinfo.parise_count = [NSString stringWithFormat:@"%d",[commentinfo.parise_count intValue] - 1];
                [commentinfo.pariseList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([[JHUserInfo getUserInfo].userId isEqualToString:[NSString stringWithFormat:@"%@",obj[@"user_id"]]]) {
                        [commentinfo.pariseList removeObject:obj];
                    }
                }];
                commentinfo.praise_history = @"0";
            }
            CommentFrame *commentf=[[CommentFrame alloc]init];
            commentf.commentinfo=commentinfo;
            [self.dataArray replaceObjectAtIndex:indexPath.section withObject:commentf];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}
#pragma mark -------------- 校园圈评论回复
- (void)clickReplay:(CommentInfo *)commentinfo andindexPath:(NSIndexPath *)indexPath replayNum:(NSInteger)repNum{
    __weak typeof(self) weakSelf = self;
    self.inputViewStyleDefault = [self inputViewWithStyle:InputViewStyleDefault];
    self.inputViewStyleDefault.delegate = self;
    [self.view addSubview:self.inputViewStyleDefault];
    /** 发送按钮点击事件 */
    self.inputViewStyleDefault.sendBlcok = ^(NSString *text) {
        if (strIsEmpty(text)) {
            [Global showActivityWithView:weakSelf.view withText:@"回复内容不能为空"];
            return;
        }
        [weakSelf.inputViewStyleDefault hide];//隐藏输入框
        YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setValue:commentinfo.topic_id forKey:@"otherId"];   //动态的topicId 赞目标id
        if (repNum != 1000) {
            ReplayInfo *replayInfo = commentinfo.comment_list[repNum];
            [dic setValue:replayInfo.user_id forKey:@"toUserId"];//被回复的目标用户ID 可不传
        }
        [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
        [dic setValue:text forKey:@"content"]; //评论内容
        [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppFriendAddComment] andParmas:dic andComplition:^(id response, BOOL isuccess) {
            if (isuccess) {
                [Global showActivityWithView:weakSelf.view withText:@"回复成功"];
                
                commentinfo.reply_count = [NSString stringWithFormat:@"%d",[commentinfo.reply_count intValue] + 1];
                NSMutableDictionary *userDic = [[NSMutableDictionary alloc]init];
                userDic[@"comment_id"] = response[@"comment_id"];
                userDic[@"user_id"]=[JHUserInfo getUserInfo].userId;
                userDic[@"user_name"]=[JHUserInfo getUserInfo].nick_name;
                if (repNum != 1000) {
                    ReplayInfo *repalyInfo = commentinfo.comment_list[repNum];
                    userDic[@"to_user_name"]=repalyInfo.user_name;
                }
                userDic[@"content"]=text;
                [commentinfo.comment_list addObject:[ReplayInfo mj_objectWithKeyValues:userDic]];
                CommentFrame *commentf=[[CommentFrame alloc]init];
                commentf.commentinfo=commentinfo;
                [weakSelf.dataArray replaceObjectAtIndex:indexPath.section withObject:commentf];
                [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
            }
        }];

    };
    [self.inputViewStyleDefault show];
    
}
#pragma mark - 删除动态
- (void)deleteComment:(CommentInfo *)commentInfo andindexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf = self;
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:commentInfo.topic_id forKey:@"topicId"];   //动态的topicId 赞目标id
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppFriendDeleteTopic] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [Global showActivityWithView:self.view withText:@"删除动态成功"];
            [weakSelf.dataArray removeObjectAtIndex:indexPath.section];
            [weakSelf.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}
#pragma mark - 删除回复
- (void)deleteReplay:(ReplayInfo *)replayInfo andindexPath:(NSIndexPath *)indexPath  replayNum:(NSInteger)repNum{
    __weak typeof(self) weakSelf = self;
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:replayInfo.comment_id forKey:@"commentId"];   //动态的topicId 赞目标id
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppFriendDeleteComment] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            CommentFrame *commentf=self.dataArray[indexPath.section];
            [commentf.commentinfo.comment_list removeObjectAtIndex:repNum];
            commentf.commentinfo=commentf.commentinfo;  //删除之后必须要重新赋值，否则模型不会刷新
            [weakSelf.dataArray replaceObjectAtIndex:indexPath.section withObject:commentf];
            [Global showActivityWithView:self.view withText:@"删除评论成功"];
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}
-(XHInputView *)inputViewWithStyle:(InputViewStyle)style{
    
    XHInputView *inputView = [[XHInputView alloc] initWithStyle:style];
    //设置最大输入字数
    inputView.maxCount = 50;
    //输入框颜色
    inputView.textViewBackgroundColor = [UIColor groupTableViewBackgroundColor];
    //占位符
    inputView.placeholder = @"请输入...";
    return inputView;
}

#pragma mark - 发表
- (void)publish{
    SendFriendCircleViewController *sendFriendCircleVC = [[ SendFriendCircleViewController alloc]init];
    __weak typeof(self) weakSelf = self;
    sendFriendCircleVC.sendFriendCircleBlock = ^{
        [weakSelf creatDataList];
    };
    sendFriendCircleVC.sendType = KSendFriendCircle;
    sendFriendCircleVC.titleStr = @"发帖子";
    [self.navigationController pushViewController:sendFriendCircleVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
